package com.dk.auth.core.service;

import com.dk.common.distribute.DistObjectFactory;
import com.dk.common.distribute.cache.DistCache;
import com.dk.common.exception.BusinessException;
import com.dk.common.model.UserDTO;
import com.dk.shared.defs.SharedDefs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.UUID;

@Service
public class LoginService {

    @Autowired
    private UserService userService;

    @Autowired
    private DistObjectFactory distObjectFactory;
    @Autowired
    private ServerProperties properties;

    public UserDTO login(String userName, String password) {
        UserDTO userDTO =  userService.findByName(userName)
                .orElseThrow(() ->new BusinessException("账户名或者密码错误！"));
        if(!Objects.equals(userDTO.getPassword(),password)){
            throw new BusinessException("账户名或者密码错误！");
        }
        String tokenId = UUID.randomUUID().toString();
        DistCache<String, UserDTO> cache = distObjectFactory.getCache(SharedDefs.USER_INFO_KEY);
        long timeout = properties.getServlet().getSession().getTimeout().getSeconds();
        cache.put(tokenId,userDTO,timeout * 1000);
        return userDTO.withToken(tokenId);
    }
}
